package com.mzj.saas.util;

import cn.hutool.core.convert.Convert;
import com.haixiaoke.saas.repository.exception.BizException;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.util.ServletUtil;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class LoginUserUtil {

    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 获取登录用户id
     */
    public String getId() {
        TokenRedisVo tokenRedis = getTokenRedis();
        return tokenRedis.getId();
    }

    /**
     * 获取登录用户名称
     */
    public String getName() {
        TokenRedisVo tokenRedis = getTokenRedis();
        return tokenRedis.getName();
    }

    /**
     * 获取登录用户手机号
     */
    public String getPhone() {
        TokenRedisVo tokenRedis = getTokenRedis();
        return tokenRedis.getPhone();
    }

    /**
     * 获取登录用户的企业id
     */
    public Long getOrgId() {
        TokenRedisVo tokenRedis = getTokenRedis();
        return tokenRedis.getEnterpriseId();
    }

    /**
     * 获取登录用户的token
     */
    public String getToken() {
        return ServletUtil.getHeader("accesstoken");
    }

    /**
     * 获取登录用户的类型
     */
    public Integer getLoginType() {
        TokenRedisVo tokenRedis = getTokenRedis();
        return tokenRedis.getLoginType();
    }

    public TokenRedisVo getTokenRedis() {
        String accessToken = ServletUtil.getHeader("accesstoken");
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        if (tokenRedisVo == null) {
            Integer errorCode = Convert.toInt(StatusCode.ERROR_CODE_40001.getErrorCode());
            String errorMsg = StatusCode.ERROR_CODE_40001.getErrorMsg();
            throw new BizException(errorCode, errorMsg);
        }
        return tokenRedisVo;

    }


    /**
     * 获取登录用户的企业名称
     */
    public String getOrgName() {
        Long orgId = getOrgId();
        Optional<Department> byId = departmentRepository.findById(orgId);
        if (byId.isPresent()) {
            Department department = byId.get();
            return department.getName();
        }else {
            return null;
        }
    }
}
